package com.tv.cms.system.permission.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tv.cms.system.account.model.Account;
import com.tv.cms.system.account.service.AccountService;
import com.tv.cms.system.permission.model.Permission;
import com.tv.cms.system.permission.service.PermissionService;
import com.tv.cms.utils.Result;
import com.tv.cms.utils.ResultCode;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * TODO
 *
 * @author
 * @date
 **/
@RestController
@RequestMapping("permission")
public class PermissionController {

    @Resource
    private PermissionService service;
    @Resource
    private AccountService accountService;

    @GetMapping("get")
    public Result<List<Permission>> get(@RequestParam Map<String,Object> params){
        List<Permission> list = service.list(new QueryWrapper<Permission>().eq("role_id", params.get("roleId")).eq("status", 1));
        return new Result<List<Permission>>().OKDATA(list);
    }

    @PostMapping("save")
    public Result save(@RequestBody Permission permission){
        List<String> itemList = permission.getItemList();
        Integer roleId = permission.getRoleId();
        if(roleId == null || itemList == null || itemList.isEmpty()){
            return new Result<>(ResultCode.FAILURE.getCode(), "传参错误", null);
        }
        List<Permission> list = new ArrayList<>();
        Permission permission1 ;
        for (String string : itemList) {
            permission1 = new Permission();
            permission1.setRoleId(roleId);
            permission1.setItem(string);
            permission1.setStatus(1);
            permission1.setCreateDate(new Date());
            permission1.setUpdateDate(new Date());
            permission1.setCreateBy(StpUtil.getLoginIdAsInt());
            permission1.setUpdateBy(StpUtil.getLoginIdAsInt());
            list.add(permission1);
        }
        service.remove(new QueryWrapper<Permission>().eq("role_id",roleId));
        List<Account> accountList = accountService.list(new QueryWrapper<Account>().eq("role_id", roleId));
        for (Account account : accountList) {
            StpUtil.logout(account.getId());
        }
        boolean save = service.saveBatch(list);
        return save ? Result.OK() : Result.FAILURE();
    }
}
